package com.fgba.express.security;



import com.fgba.express.comm.enums.State;
import com.fgba.express.data.entity.User;
import com.fgba.express.data.service.IUserService;
import com.fgba.express.util.BeanContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author fgba
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        IUserService userService = BeanContextUtil.getBean(IUserService.class);
        User user = userService.getUserByUsername(username);
        List<GrantedAuthority> authorities;
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码不正确!");
        }
        authorities = getAuthorities(userService.getUserAuthorityInfo(user.getId()));

        //用户状态
        return new AccountUser(user.getId(), user.getUsername(), user.getPassword(),
                user.getState().equals(State.STATUS_AVAILABLE), true, true, true, authorities);
    }

    public List<GrantedAuthority> getAuthorities(String authorityInfo) {
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityInfo);
    }
}
